<template>
  <div class="publicpageview">
    <div class="page-layout">
      <!-- 左侧管理年度区域 -->
      <div class="left-panel">
        <div class="year-panel">
          <h3 class="panel-title">管理年度</h3>
          <div class="year-list">
            <div v-for="year in yearList" :key="year.value"
              :class="['year-item', { 'active': selectedYear === year.value }]" @click="handleYearChange(year.value)">
              <span class="year-text">{{ year.label }}</span>
              <span class="year-count">({{ year.count }})</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧内容区域 -->
      <div class="right-panel">
        <div class="publicformview">
          <el-form :inline="true" :model="listQuery" size="mini" ref="searchForm">
            <el-row :gutter="20">
              <!-- 第一行 -->
              <el-col :span="6">
                <el-form-item label="区房屋管理单位：" prop="districtId">
                  <CompanySelect v-model="listQuery.districtId" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="管理部(分中心)：" prop="houseAdminId">
                  <DeptBrowser v-model="listQuery.houseAdminId" :queryDistrictId="listQuery.districtId" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="紧急程度：" prop="urgency">
                  <el-select v-model="listQuery.urgency" placeholder="请选择紧急程度" clearable>
                    <el-option v-for="item in dictData.urgencyDict" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="任务类型：" prop="type">
                  <el-select v-model="listQuery.type" placeholder="全部" style="width: 100%">
                    <el-option label="全部" value=""></el-option>
                    <el-option v-for="item in dictData.taskTypeDict" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <!-- 新增一行放发布等级 -->
              <el-col :span="6">
                <el-form-item label="发布等级：" prop="levels">
                  <el-select v-model="listQuery.levels" placeholder="请选择发布等级" clearable style="width: 100%">
                    <el-option v-for="item in dictData.levelDict" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <!-- 第二行 -->
              <el-col :span="8">
                <el-form-item label="任务日期：" prop="taskDateRange">
                  <el-date-picker v-model="listQuery.startTime" type="date" placeholder="开始日期" value-format="yyyy-MM-dd"
                    style="width: 45%">
                  </el-date-picker>
                  <span style="margin: 0 8px;">~</span>
                  <el-date-picker v-model="listQuery.endTime" type="date" placeholder="结束日期" value-format="yyyy-MM-dd"
                    style="width: 45%">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="16">
                <div style="text-align: right;">
                  <el-button size="mini" type="primary" @click="handleSearch">查询</el-button>
                  <el-button size="mini" @click="resetForm('searchForm')">重置</el-button>
                </div>
              </el-col>
            </el-row>
          </el-form>
        </div>

        <div class="publitableview">
          <el-button type="primary" size="mini" @click="handleAddTask">巡查任务录入</el-button>
          <el-table v-loading="listLoading" :data="list" border fit highlight-current-row size="mini">
            <el-table-column align="center" label="序号" type="index" width="60">
            </el-table-column>

            <el-table-column align="center" label="任务编号" prop="taskNo" width="130">
            </el-table-column>

            <el-table-column align="center" label="检查计划名称" prop="name" min-width="150">
            </el-table-column>

            <el-table-column align="center" label="紧急程度" prop="urgency" width="80">
              <template slot-scope="scope">
                {{ getDictName('urgencyDict', scope.row.urgency) }}
              </template>
            </el-table-column>

            <el-table-column align="center" label="发布单位" prop="unitSubmit" width="120">
              <template slot-scope="scope">
                <CompanySelect v-model="scope.row.unitSubmit" :disabled="true" />
              </template>
            </el-table-column>

            <el-table-column align="center" label="发布等级" prop="levels" width="80">
              <template slot-scope="scope">
                {{ getDictName('levelDict', scope.row.levels) }}
              </template>
            </el-table-column>

            <el-table-column align="center" label="接收单位" prop="unitRecive" width="180">
              <template slot-scope="scope">
                <CompanySelect v-if="scope.row.levels==1" v-model="scope.row.unitRecive" :disabled="true" multiple />
                <span v-else>{{buunitRecive(scope.row.unitRecive)}}</span>
              </template>
            </el-table-column>

            <el-table-column align="center" label="任务类型" prop="type" width="140">
              <template slot-scope="scope">
                {{ getDictName('taskTypeDict', scope.row.type) }}
              </template>
            </el-table-column>

            <el-table-column align="center" label="周期类型" prop="cycleType" width="80">
              <template slot-scope="scope">
                {{ getDictName('cycleTypeDict', scope.row.cycleType) }}
              </template>
            </el-table-column>

            <el-table-column align="center" label="任务时间" prop="startTime" width="200">
              <template slot-scope="scope">
                <div>
                  {{ formatDate(scope.row.startTime) }}~{{ formatDate(scope.row.endTime) }}

                </div>
              </template>
            </el-table-column>

            <el-table-column align="center" label="状态" prop="status" width="80">
              <template slot-scope="scope">
                {{ getDictName('statusDict', scope.row.status) }}
              </template>
            </el-table-column>

            <el-table-column align="center" label="操作" width="200" fixed="right">
              <template slot-scope="scope">
                <el-button type="text" size="mini" @click="handleViewAttachments(scope.row)">查看附件</el-button>
                <el-button type="text" size="mini" @click="handleUpdate(scope.row)">修改</el-button>
                <el-button type="text" size="mini" @click="handleView(scope.row)">详情</el-button>
                <el-button type="text" size="mini" @click="handleDelete(scope.row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="publicpaginationview">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
              :current-page="listQuery.pageNum" background :page-sizes="[10, 20, 50, 100]"
              :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total" small>
            </el-pagination>
          </div>
        </div>
      </div>
    </div>

    <!-- 巡查任务弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="800px" @close="handleDialogClose">
      <el-form :model="formData" :rules="formRules" ref="taskForm" label-width="150px" size="small" class="safe-form">
        <el-form-item label="任务编号：" prop="taskNo">
          <el-input v-model="formData.taskNo" :disabled="isReadonly" placeholder="请输入任务编号"></el-input>
        </el-form-item>

        <el-form-item label="检查计划名称：" prop="name">
          <el-input v-model="formData.name" :disabled="isReadonly" placeholder="请输入检查计划名称"></el-input>
        </el-form-item>

        <el-form-item label="紧急程度：" prop="urgency">
          <el-select v-model="formData.urgency" :disabled="isReadonly" placeholder="请选择紧急程度" style="width: 100%">
            <el-option v-for="item in dictData.urgencyDict" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="发布等级：" prop="levels">
          <el-select v-if="!isReadonly" v-model="formData.levels" placeholder="请选择发布等级" style="width: 100%">
            <el-option v-for="item in dictData.levelDict" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
          <span v-else>{{ getDictName('levelDict', formData.levels) }}</span>
        </el-form-item>
        <el-form-item label="发布单位：" prop="unitSubmit">
          <CompanySelect v-model="formData.unitSubmit" :disabled="isReadonly" />
        </el-form-item>

        <el-form-item v-if="formData.levels==1" label="接收单位：" prop="unitRecive">
          <CompanySelect v-model="formData.unitRecive" :disabled="isReadonly" multiple />
        </el-form-item>

        <el-form-item v-else label="接收单位：" prop="unitRecive">
          <DeptBrowser v-model="formData.unitRecive" :queryDistrictId="formData.unitSubmit" multiple />
        </el-form-item>

        <!-- <el-form-item label="管理部(分中心)：" prop="houseAdminId">
				  <DeptBrowser v-model="formData.houseAdminId" :queryDistrictId="formData.unitSubmit" />
				</el-form-item> -->





        <el-form-item label="任务类型：" prop="type">
          <el-select v-if="!isReadonly" v-model="formData.type" placeholder="请选择任务类型" style="width: 100%">
            <el-option v-for="item in dictData.taskTypeDict" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
          <span v-else>{{ getDictName('taskTypeDict', formData.type) }}</span>
        </el-form-item>

        <el-form-item label="周期类型：" prop="cycleType">
          <el-select v-if="!isReadonly" v-model="formData.cycleType" placeholder="请选择周期类型" style="width: 100%">
            <el-option v-for="item in dictData.cycleTypeDict" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
          <span v-else>{{ getDictName('cycleTypeDict', formData.cycleType) }}</span>
        </el-form-item>

        <el-form-item label="开始时间：" prop="startTime">
          <el-date-picker v-model="formData.startTime" :disabled="isReadonly" type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss" placeholder="请选择开始时间" style="width: 100%">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="结束时间：" prop="endTime">
          <el-date-picker v-model="formData.endTime" :disabled="isReadonly" type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss" placeholder="请选择结束时间" style="width: 100%">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="市级要求：" prop="requirements">
          <el-input type="textarea" v-model="formData.requirements" :disabled="isReadonly"
            placeholder="请输入市级要求"></el-input>
        </el-form-item>

        <el-form-item label="管理年份：" prop="year">
          <el-date-picker v-if="!isReadonly" v-model="formData.years" type="year" :disabled="isReadonly"
            placeholder="请选择管理年份" value-format="yyyy" style="width: 100%">
          </el-date-picker>
          <span v-else>{{ formData.years }}</span>
        </el-form-item>

        <el-form-item label="状态：" prop="status">
          <el-select v-if="!isReadonly" v-model="formData.status" placeholder="请选择状态" style="width: 100%">
            <el-option v-for="item in dictData.statusDict" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
          <span v-else>{{ getDictName('statusDict', formData.status) }}</span>
        </el-form-item>

        <el-form-item label="文件名称：" prop="processAttachments">
          <div v-if="isReadonly && formData.processAttachments && formData.processAttachments.length > 0">
            <div v-for="(file, index) in formData.processAttachments" :key="index" class="file-list-item">
              <el-button type="text">{{ file.name }}</el-button>
            </div>
          </div>
          <el-button v-else type="text" :disabled="isReadonly"
            @click="handleUploadFile('processAttachments')">点击上传</el-button>
        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">{{ isReadonly ? '关 闭' : '取 消' }}</el-button>
        <el-button v-if="!isReadonly" type="primary" @click="handleSubmit" :loading="submitLoading">保 存</el-button>
      </div>
    </el-dialog>

    <!-- 查看附件弹窗 -->
    <el-dialog title="查看附件" :visible.sync="attachmentDialogVisible" width="800px" @close="handleAttachmentDialogClose">
      <div class="attachment-view">
        <div v-for="(file, index) in currentAttachments" :key="index" class="attachment-item">
          <div class="file-icon" :class="getFileIconClass(file.type)">
            <div v-if="file.type === 'pdf'" class="pdf-lines">
              <span></span>
            </div>
            <div v-else-if="file.type === 'word'" class="word-icon">W</div>
            <div v-else-if="file.type === 'excel'" class="excel-icon">E</div>
            <div v-else class="default-icon">文</div>
            <div class="file-text">{{ getFileTypeText(file.type) }}</div>
          </div>
          <div class="file-name">{{ file.name }}</div>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="attachmentDialogVisible = false">返回</el-button>
      </div>
    </el-dialog>


    <el-dialog title="上传文件" :visible.sync="fileUploadDialogVisible" width="600px" @close="handleFileUploadDialogClose">
      <div class="upload-container">
        <el-upload class="upload-dragger" drag :action="uploadAction" :file-list="currentFileList"
          :on-success="handleFileUploadSuccess" :on-error="handleFileUploadError" :on-change="handleFileUploadChange"
          :before-upload="beforeFileUpload" :auto-upload="false" multiple ref="fileUpload">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">
            请将文件拖动到此处，或<em>点击上传</em>
          </div>
        </el-upload>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="fileUploadDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleConfirmFileUpload">确 认</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { getHouseAdmin } from '@/api/common'
import { getSurveyTaskList, addSurveyTask, updateSurveyTask, getSurveyTaskDetail, deleteSurveyTask, getSurveyTaskYearList } from '@/api/safe/fangwuanquankancha/xuncharenwu'
import CompanySelect from "@/components/commonSelect/companySelect.vue"
import DeptBrowser from "@/components/SysBrowser/DeptBrowser.vue"
import { convertObjectIntegersToStrings } from "@/utils/dataUtils";
import { formatDate } from "@/utils/dateUtils";

export default {
  name: 'XunchaRenwu',
  components: { CompanySelect, DeptBrowser },

  data() {
    return {
      selectedYear: new Date().getFullYear().toString(),
      yearList: [],
      listQuery: {
        pageNum: 1,
        pageSize: 20,
        districtId: "",        // 区房屋管理单位ID
        endTime: "",           // 周期结束时间
        houseAdminId: "",      // 管理部(分中心)ID
        startTime: "",         // 周期开始时间
        type: "",              // 安全监管任务类型(1上门检查; 2定期检查; 3专项检查; 4应急检查)
        urgency: "",           // 紧急程度
        levels: "",      // 发布等级(1市发布; 2区发布)
        year: new Date().getFullYear().toString()  // 管理年度
      },
      total: 0,
      list: [],
      listLoading: false,
      dialogVisible: false,
      attachmentDialogVisible: false,
      submitLoading: false,
      dialogTitle: "新增巡查任务",
      isReadonly: false,
      currentEditId: null,
      currentAttachments: [],
      uploadAction: "http://125.39.77.18:9021/mall-admin/fileUpload/upload",
      // 字典数据
      dictData: {
        // 紧急程度字典
        urgencyDict: [
          { id: '1', name: '一级' },
          { id: '2', name: '二级' },
          { id: '3', name: '三级' },
          { id: '4', name: '四级' },
          { id: '5', name: '五级' }
        ],
        // 任务类型字典
        taskTypeDict: [
          { id: '1', name: '严重损坏房屋' },
          { id: '2', name: '地铁和深基坑施工项目' },
          { id: '3', name: '汛期巡查房屋' },
          { id: '4', name: '冬季巡查房屋' },
          { id: '5', name: '其他(专项)房屋)' }
        ],
        // 周期类型字典 (1每周；2每月；3每季度；4每年；5一次性)
        cycleTypeDict: [
          { id: '1', name: '每周' },
          { id: '2', name: '每月' },
          { id: '3', name: '每季度' },
          { id: '4', name: '每年' },
          { id: '5', name: '一次性' }
        ],
        // 状态字典 (0代办；1已办)
        statusDict: [
          { id: '0', name: '待办' },
          { id: '1', name: '已办' }
        ],
        // 发布等级字典 (1市发布；2区发布)
        levelDict: [
          { id: '1', name: '市发布' },
          { id: '2', name: '区发布' }
        ]
      },
      formData: {
        blockId: "",
        blockName: "",
        cycleType: "",
        detectId: "",
        detectName: "",
        endTime: "",
        houseAdminId: "",
        houseAdminName: "",
        name: "",
        levels: "",
        requirements: "",
        startTime: "",
        status: "",
        taskNo: "",
        type: "",
        unitRecive: "",
        unitSubmit: "",
        urgency: "",
        years: new Date().getFullYear().toString(),
        processAttachments: []
      },
      formRules: {
        taskNo: [
          { required: true, message: '请输入任务编号', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入检查计划名称', trigger: 'blur' }
        ],
        urgency: [
          { required: true, message: '请选择紧急程度', trigger: 'change' }
        ],
        unitSubmit: [
          { required: true, message: '请输入发布单位', trigger: 'blur' }
        ],
        unitRecive: [
          { required: true, message: '请输入接收单位', trigger: 'blur' }
        ],
        levels: [
          { required: true, message: '请选择发布等级', trigger: 'change' }
        ],
        houseAdminId: [
          { required: true, message: '请选择管理部(分中心)', trigger: 'change' }
        ],
        type: [
          { required: true, message: '请选择任务类型', trigger: 'change' }
        ],
        cycleType: [
          { required: true, message: '请选择周期类型', trigger: 'change' }
        ],
        startTime: [
          { required: true, message: '请选择开始时间', trigger: 'change' }
        ],
        endTime: [
          { required: true, message: '请选择结束时间', trigger: 'change' }
        ],
        requirements: [
          { required: true, message: '请输入市级要求', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      },
      bumenList: [],
      fileUploadDialogVisible: false,
      currentFileList: [],
    };
  },

  computed: {
    getTaskTypeDisplayName() {
      const taskTypeMap = {
        '1': '上门检查',
        '2': '定期巡查',
        '3': '专项检查',
        '4': '应急检查'
      };
      return function (value) {
        return taskTypeMap[value] || value;
      };
    }
  },

  mounted() {
    this.getList();
    let data = {
      pageNum: 1,
      pageSize: 9999
    }
    getHouseAdmin(data).then(res => {
      this.bumenList = res.data.list
    })
  },

  methods: {

    handleUploadFile() {

      this.currentFileList = [];
      this.fileUploadDialogVisible = true;
    },

    handleFileUploadDialogClose() {
      this.currentFileList = [];

      this.$refs.fileUpload.clearFiles();
    },

    beforeFileUpload(file) {
      const isValidType = file.type.includes('image/') ||
        file.type === 'application/pdf' ||
        file.type === 'application/vnd.ms-excel' ||
        file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
        file.type === 'application/msword' ||
        file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';

      if (!isValidType) {
        this.$message.error('只能上传图片、PDF、Excel、Word文件！');
        return false;
      }

      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isLt10M) {
        this.$message.error('上传文件大小不能超过 10MB!');
        return false;
      }

      return true;
    },

    handleFileUploadChange(file, fileList) {
      this.currentFileList = fileList;
    },


    handleFileUploadSuccess(response, file) {
      this.$message.success(`文件 ${file.name} 上传成功`);
    },

    handleFileUploadError(err, file) {
      this.$message.error(`文件 ${file.name} 上传失败`);
    },

    handleConfirmFileUpload() {
      if (this.currentFileList.length === 0) {
        this.$message.warning('请先选择要上传的文件');
        return;
      }

      const uploadedFiles = this.currentFileList.map(file => {
        let fileType = 'default';
        if (file.raw.type.includes('image/')) {
          fileType = 'image';
        } else if (file.raw.type === 'application/pdf') {
          fileType = 'pdf';
        } else if (file.raw.type.includes('excel') || file.raw.type.includes('spreadsheet')) {
          fileType = 'excel';
        } else if (file.raw.type.includes('word') || file.raw.type.includes('document')) {
          fileType = 'word';
        }

        return {
          name: file.name,
          type: fileType,
          size: file.size,
          url: URL.createObjectURL(file.raw)
        };
      });
      this.formData.processAttachments = [...this.formData.processAttachments, ...uploadedFiles];
      this.fileUploadDialogVisible = false;
      this.$message.success('文件上传成功！');
    },

    buunitRecive(unitRecive) {
      let name = ''
      this.bumenList.forEach((item, index) => {
        unitRecive.split(",").forEach((it, idx) => {
          if (it == item.aid) {
            console.log(it, item.aid)
            name = item.aname
          }
        })
      })
      return name
    },
    // 格式化日期
    formatDate(dateString) {
      return formatDate(dateString);
    },

    // 获取年度列表
    getYearList() {
      getSurveyTaskYearList().then(response => {
        if (response.code === 200) {
          this.yearList = response.data.map(item => ({
            value: item.years,
            label: item.years + '年',
            count: item.count
          })) || [];

          // 如果当前选中的年度不在列表中，选择第一个年度
          if (this.yearList.length > 0) {
            const currentYearExists = this.yearList.some(year => year.value === this.selectedYear);
            if (!currentYearExists) {
              this.selectedYear = this.yearList[0].value;
              this.listQuery.year = this.selectedYear;
            }
          }
        } else {
          this.$message.error(response.message || '获取年度列表失败');
        }
      }).catch(error => {
        console.error('获取年度列表失败:', error);
        this.$message.error('获取年度列表失败');
      });
    },

    // 分页大小改变
    handleSizeChange(val) {
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
      this.getList();
    },
    // 当前页改变
    handleCurrentChange(val) {
      this.listQuery.pageNum = val;
      this.getList();
    },
    // 获取列表数据
    getList() {
      this.getYearList();
      this.listLoading = true;

      // 处理日期范围
      const params = { ...this.listQuery };
      if (this.listQuery.taskDateRange && this.listQuery.taskDateRange.length === 2) {
        params.startTime = this.listQuery.taskDateRange[0];
        params.endTime = this.listQuery.taskDateRange[1];
      }
      delete params.taskDateRange;
      for (let key in params) {
        if (!params[key]) {
          delete params[key]
        }
      }
      getSurveyTaskList(params).then(response => {
        if (response.code === 200) {
          this.list = response.data.list || [];
          this.total = response.data.total || 0;
        } else {
          this.$message.error(response.message || '获取数据失败');
        }
        this.listLoading = false;
      }).catch(error => {
        console.error('获取巡查任务列表失败:', error);
        this.$message.error('获取数据失败');
        this.listLoading = false;
      });
    },
    // 搜索
    handleSearch() {
      this.listQuery.pageNum = 1;
      this.getList();
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.getList();
      this.listQuery.startTime = ''
      this.listQuery.endTime = ''
    },
    // 年度切换
    handleYearChange(year) {
      this.selectedYear = year;
      this.listQuery.year = year;
      this.listQuery.pageNum = 1;
      this.getList();
      this.$message.success(`切换到${year}年数据`);
    },
    // 新增巡查任务
    handleAddTask() {
      this.dialogTitle = "新增巡查任务";
      this.isReadonly = false;
      this.currentEditId = null;
      this.dialogVisible = true;
      this.resetFormData();
    },
    // 弹窗关闭
    handleDialogClose() {
      this.resetFormData();
      this.$refs.taskForm.resetFields();
    },
    // 重置表单数据
    resetFormData() {
      this.formData = {
        id: "",
        blockId: "",
        blockName: "",
        createTime: "",
        cycleType: "",
        detectId: "",
        detectName: "",
        endTime: "",
        houseAdminId: "",
        houseAdminName: "",
        name: "",
        levels: "",
        requirements: "",
        startTime: "",
        status: "",
        taskNo: "",
        type: "",
        unitRecive: "",
        unitSubmit: "",
        urgency: "",
        year: "",
        processAttachments: []
      };
    },
    // 表单提交
    handleSubmit() {

      this.$refs.taskForm.validate((valid) => {
        if (valid) {
          this.submitLoading = true;

          const apiCall = this.currentEditId ? updateSurveyTask : addSurveyTask;
          const data = { ...this.formData, file: JSON.stringify(this.formData.processAttachments) };

          delete data.createTime;
          // if(data.levels == 1){
          // 	data.houseAdminId = ''
          // }else if(data.levels==2){

          // }


          apiCall(data).then(response => {
            this.submitLoading = false;
            if (response.code === 200) {
              this.dialogVisible = false;
              this.$message.success(this.currentEditId ? '修改成功！' : '新增成功！');
              this.getList();
            } else {
              this.$message.error(response.message || '操作失败');
            }
          }).catch(error => {
            this.submitLoading = false;
            console.error('提交数据失败:', error);
            this.$message.error('操作失败');
          });
        } else {
          this.$message.error('请填写完整信息');
          return false;
        }
      });
    },
    // 查看详情
    handleView(row) {
      this.dialogTitle = "查看巡查任务详情";
      this.isReadonly = true;
      this.currentEditId = row.id;

      getSurveyTaskDetail(row.id).then(response => {
        if (response.code === 200) {
          this.formData = convertObjectIntegersToStrings(response.data) || {};
          this.formData.processAttachments = response.data.file ? JSON.parse(response.data.file) : [],
            this.formData.level = response.data.levels
          this.dialogVisible = true;
        } else {
          this.$message.error(response.message || '获取详情失败');
        }
      }).catch(error => {
        console.error('获取详情失败:', error);
        this.$message.error('获取详情失败');
      });
    },
    // 修改记录
    handleUpdate(row) {
      this.dialogTitle = "修改巡查任务";
      this.isReadonly = false;
      this.currentEditId = row.id;

      getSurveyTaskDetail(row.id).then(response => {
        if (response.code === 200) {
          this.formData = convertObjectIntegersToStrings(response.data) || {};
          this.formData.processAttachments = response.data.file ? JSON.parse(response.data.file) : [],
            this.dialogVisible = true;
        } else {
          this.$message.error(response.message || '获取详情失败');
        }
      }).catch(error => {
        console.error('获取详情失败:', error);
        this.$message.error('获取详情失败');
      });
    },

    // 查看附件
    handleViewAttachments(row) {
      this.currentAttachments = row.attachments || [];
      this.attachmentDialogVisible = true;
    },
    // 附件弹窗关闭
    handleAttachmentDialogClose() {
      this.attachmentDialogVisible = false;
      this.currentAttachments = [];
    },
    // 获取文件图标类名
    getFileIconClass(type) {
      const classMap = {
        'pdf': 'file-pdf',
        'word': 'file-word',
        'excel': 'file-excel',
        'image': 'file-image',
        'default': 'file-default'
      };
      return classMap[type] || classMap['default'];
    },
    // 获取文件类型文本
    getFileTypeText(type) {
      const textMap = {
        'pdf': 'PDF',
        'word': 'DOC',
        'excel': 'XLS',
        'image': 'IMG',
        'default': '文件'
      };
      return textMap[type] || textMap['default'];
    },
    // 删除记录
    handleDelete(id) {
      this.$confirm('此操作将删除该条内容，请确认是否继续操作？', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteSurveyTask(id).then(response => {
          if (response.code === 200) {
            this.$message.success('删除成功!');
            this.getList();
          } else {
            this.$message.error(response.message || '删除失败');
          }
        }).catch(error => {
          console.error('删除失败:', error);
          this.$message.error('删除失败');
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    // 通用字典名称查找方法
    getDictName(dictType, id) {
      if (!this.dictData[dictType]) return id;
      const item = this.dictData[dictType].find(item => item.id === String(id));
      return item ? item.name : id;
    }
  }
};
</script>

<style scoped>
/* 页面布局样式 */
.page-layout {
  display: flex;
  height: 100%;
  gap: 5px;
}

/* 左侧面板样式 */
.left-panel {
  width: 240px;
  flex-shrink: 0;
}

.year-panel {
  background: #fff;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
  padding: 0;
  overflow: hidden;
}

.panel-title {
  margin: 0;
  padding: 16px 20px;
  background: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.year-list {
  padding: 0;
}

.year-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  cursor: pointer;
  border-bottom: 1px solid #f0f0f0;
  transition: all 0.2s;
}

.year-item:last-child {
  border-bottom: none;
}

.year-item:hover {
  background-color: #f5f7fa;
}

.year-item.active {
  background-color: #ecf5ff;
  color: #409eff;
}

.year-text {
  font-size: 14px;
  font-weight: 500;
}

.year-count {
  font-size: 12px;
  color: #909399;
  background: #f0f0f0;
  padding: 2px 8px;
  border-radius: 10px;
}

.year-item.active .year-count {
  background: #409eff;
  color: #fff;
}

/* 右侧面板样式 */
.right-panel {
  flex: 1;
  min-width: 0;
}

/* 页面样式继承公共样式类 publicpageview, publicformview, publitableview */

/* 附件查看弹窗样式 */
.attachment-view {
  padding: 20px;
  min-height: 200px;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 24px;
  justify-items: center;
}

.attachment-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  width: 100%;
  max-width: 120px;
}

.file-icon {
  width: 80px;
  height: 80px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border-radius: 8px;
  position: relative;
  cursor: pointer;
  transition: transform 0.2s;
}

.file-icon:hover {
  transform: scale(1.05);
}

/* PDF文件样式 */
.file-pdf {
  background: #EF4A37;
}

.pdf-lines {
  width: 48px;
  height: 36px;
  position: relative;
  margin-bottom: 8px;
}

.pdf-lines::before,
.pdf-lines::after {
  content: '';
  position: absolute;
  left: 0;
  right: 0;
  height: 3px;
  background: white;
  border-radius: 1px;
}

.pdf-lines::before {
  top: 8px;
}

.pdf-lines::after {
  top: 16px;
}

.pdf-lines>span {
  position: absolute;
  top: 24px;
  left: 0;
  right: 0;
  height: 3px;
  background: white;
  border-radius: 1px;
}

/* Word文件样式 */
.file-word {
  background: #2B579A;
}

.word-icon {
  font-size: 32px;
  color: white;
  font-weight: bold;
  margin-bottom: 8px;
}

/* Excel文件样式 */
.file-excel {
  background: #217346;
}

.excel-icon {
  font-size: 32px;
  color: white;
  font-weight: bold;
  margin-bottom: 8px;
}

/* 图片文件样式 */
.file-image {
  background: #FF6B35;
}

/* 默认文件样式 */
.file-default {
  background: #909399;
}

.default-icon {
  font-size: 24px;
  color: white;
  font-weight: bold;
  margin-bottom: 8px;
}

.file-text {
  color: white;
  font-size: 12px;
  font-weight: bold;
  font-family: Arial, sans-serif;
}

.file-name {
  font-size: 12px;
  color: #606266;
  font-weight: 500;
  text-align: center;
  line-height: 1.4;
  word-break: break-all;
  max-width: 100%;
}
</style>